<template>
  <div>
    <el-row v-show="chapterItem.name" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <h4 style="margin: 12px">{{ chapterItem.name }}</h4>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="text"
          style="font-size: 20px"
          icon="el-icon-edit"
          @click="editChapter(chapterKey,'edit')"
        />
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="text"
          style="font-size: 20px"
          icon="el-icon-delete"
          @click="editChapter(chapterKey,'delete')"
        />
      </el-col>
    </el-row>
    <el-table :data="chapterData.children" border>
      <el-table-column label="序号" type="index" />
      <el-table-column
        v-for="(item,index) in chapterTable.columns"
        :key="index"
        :label="item.label"
        :prop="item.prop"
      >
        <template slot-scope="scope">
          <!--          编辑状态-->
          <div v-if="scope.row.is_show === 1">
            <div v-if="item.prop === 'url'">
              <el-progress
                v-if="chapterTable.sel.loading"
                :text-inside="true"
                :stroke-width="15"
                :percentage="chapterTable.sel.percentage"
              />
              <div @click="openDepotList">{{ chapterTable.sel.url_name? chapterTable.sel.url_name : '点击上传' }}</div>
            </div>

            <el-input
              v-else-if="item.prop === 'name'"
              v-model="chapterTable.sel[item.prop]"
              placeholder="请输入内容"
            />

            <el-switch
              v-else-if="item.prop === 'is_free'"
              v-model="chapterTable.sel[item.prop]"
              :active-value="1"
              :inactive-value="-1"
              active-text="是"
              inactive-text="否"
            />
            <el-date-picker
              v-else-if="item.prop === 'start_time'"
              v-model="chapterTable.sel[item.prop]"
              type="datetime"
              placeholder="直播日期"
            />
            <el-date-picker
              v-else-if="item.prop === 'end_time'"
              v-model="chapterTable.sel[item.prop]"
              type="datetime"
              placeholder="结束日期"
            />
<!--            <el-date-picker-->
<!--              v-else-if="item.prop === 'end_time'"-->
<!--              v-model="chapterTable.sel[item.prop]"-->
<!--              type="date"-->
<!--              placeholder="结束日期"-->
<!--              format="yyyy 年 MM 月 dd 日"-->
<!--              value-format="yyyy-MM-dd">-->
<!--            </el-date-picker>-->
<!--            <el-date-picker-->
<!--              v-else-if="item.prop === 'start_time'"-->
<!--              v-model="chapterTable.sel[item.prop]"-->
<!--              type="datetimerange"-->
<!--              range-separator="至"-->
<!--              start-placeholder="开始日期"-->
<!--              end-placeholder="结束日期"-->
<!--            >-->
<!--            </el-date-picker>-->

          </div>
          <!--          查看状态-->
          <div v-else>
            <el-button
              v-if="item.prop === 'url'"
              type="text"
              @click="preview(scope.row.url)"
            >{{ scope.row.url_name }}</el-button>
            <span v-else-if="item.prop === 'exercises'">
              <router-link
                v-if="scope.row.is_contain_exercise === 1"
                :to="{name:'subject',
                      params: {
                        id:chapterItem.course_id,
                        chapter_id: scope.row.id,
                        link_type: 1,
                      }}"
              >
                <el-button type="text">章节习题</el-button>
              </router-link>
              <el-button v-else type="text" @click="addExercises(scope.row.id)">添加习题</el-button>
            </span>
            <span v-else-if="item.prop == 'is_free'">
              <el-button type="text">{{ scope.row.is_free==1?'是':'否' }}</el-button>
            </span>
            <span v-else-if="item.prop === 'start_time'">
              <el-button type="text">{{ scope.row.start_time }}</el-button>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="editRow(scope.row,scope.$index)">编辑</el-button>
          <el-button
            :disabled="scope.row.is_show === 0 || scope.row.is_show === -1"
            type="text"
            @click="saveRow(scope.row,scope.$index)"
          >保存</el-button>
          <el-button type="text" @click="deleteRow(scope.$index,chapterData.children)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="addsonchapter" @click="addSonchapter()">
      <i class="el-icon-plus" />添加子章节
    </div>
    <Exercises :visible="visible" @cancel="cancel" @submitForm="submitForm" />
    <Video :show-video="showVideo" :play-url="playUrl" @handleHideModal="handleHideModal" />
    <!-- 媒体库-->
    <el-drawer
      title="媒体库"
      :visible.sync="drawer"
      size="45%"
    >
      <!--  搜索栏-->
      <el-form :inline="true" :model="depotForm" class="demo-form-inline">
        <el-form-item label="文件名">
          <el-input v-model="depotForm.video_name" placeholder="搜索文件名" />
        </el-form-item>
        <el-form-item label="适用地区">
          <el-select v-model="depotForm.province" placeholder="适用地区" @change="changeCity()">
            <el-option v-for="(item,i) in cityList" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="科目">
          <el-select v-model="depotForm.subject" placeholder="科目">
            <el-option v-for="(item,i) in subjectList" :key="item.id" :label="item.name" :value="item.name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmitDepot">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-upload
            :headers="headers"
            class="upload-demo"
            action
            :http-request="httpUpload"
            :show-file-list="false"
          >
            <el-button
              size="small"
              type="text"
            >普通上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <!--   媒体库内容-->
      <div v-if="depot_list.length > 0" class="depot-list">
        <div v-for="(item,i) in depot_list" class="depot-card" @click="chooseDepot(item)">
          <div>
            <!--                <img :src="item.video_img" alt="">-->
            <!--            <img :src="check_file(item)" alt="">-->
            <el-image :src="check_file(item)" />
          </div>
          <div>{{ item.video_name }}</div>
        </div>
      </div>
      <div v-else class="empty-text">暂无数据</div>
      <!--分页-->
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageIndex"
        :limit.sync="queryParams.pageSize"
        @pagination="getDepotList_fun"
      />
    </el-drawer>
  </div>
</template>

<script>
import { editChapter, addLiveChapter, editLiveChapter, delLiveChapter, delSections, getSubject, addChapter, getDepotList, getCity, getDepotInfo, addDepot, editDepot, deleteDepot } from '@/api/admin/sys-course'
import { chooseExercises } from '@/api/admin/sys-question'
import Exercises from '@/components/Exercises'
import Video from '@/components/Video'
import { clients, getNowDate } from '@/utils/index'
export default {
  name: 'Chapter',
  components: {
    Exercises,
    Video
  },
  props: {
    chapterItem: {
      type: Object,
      default: () => {
        return {}
      }
    },
    chapterKey: {
      type: Number,
      default: () => {
        return null
      }
    },
    host: {
      type: String,
      default: () => {
        return ''
      }
    },
    headers: {
      type: Object,
      default: () => {
        return {}
      }
    },
    subject: {
      type: String,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      chapterTable: {
        sel: null, // 选中行
        columns: [
          {
            prop: 'name',
            label: '子章节名称'
          },
          {
            prop: 'url',
            label: '课件名称'
          },
          {
            prop: 'exercises',
            label: '章节习题'
          },
          {
            prop: 'is_free',
            label: '是否免费'
          },
          {
            prop: 'start_time',
            label: '直播日期'
          },
          {
            prop: 'end_time',
            label: '结束日期'
          }
        ],
        loading: false,
        percentage: 0
      },
      chapterData: {
        children: []
      },
      coursewareUrl: null,
      coursewareName: null,
      visible: false,
      sectionsId: null,
      showVideo: false,
      playUrl: '',
      drawer: false,
      depot_list: [], // 媒体库列表
      depotForm: { // 媒体库搜索框
        province: '重庆'
      },
      subjectList: [], // 科目
      cityList: [],
      total: 0,
      queryParams: {
        pageIndex: 1,
        pageSize: 10
      }

    }
  },
  watch: {
    chapterItem: {
      handler(val) {
        this.chapterData = { ...val }
      }
    }
  },
  created() {
    this.chapterData = { ...this.chapterItem }
    console.log(this.chapterData)
    this.getCity_fun()
  },
  methods: {
    changeCity() { // 改变地区
      this.getSubjects()
    },
    getCity_fun() {
      getCity().then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.cityList = res?.data || []
          this.getSubjects()
        }
      })
    },
    getSubjects() { // 获取科目
      getSubject({ province: this.depotForm.province }).then(res => {
        // console.log(res)
        this.subjectList = res?.data || []
        const obj = {
          id: 0,
          name: '全部'
        }
        this.subjectList.unshift(obj)
        // console.log(this.subjectList)
      })
    },
    // 媒体库查询
    onSubmitDepot() {
      this.queryParams.pageIndex = 1
      this.getDepotList_fun()
    },
    check_file(item) { // 返回封面图
      var isVideo = /(\.mp4)/.test(item.video_name)
      // var file_type = item.video_name.split('.')[1]
      var show_file = ''
      if (isVideo) {
        show_file = item.video_img
      } else {
        show_file = item.video_path
      }
      return show_file
    },
    // 选择媒体库的文件
    chooseDepot(item) {
      // console.log(item)
      this.$set(this.chapterTable.sel, 'url', item.video_path)
      this.$set(this.chapterTable.sel, 'url_name', item.video_name)
      this.drawer = false
    },
    // 打开媒体库
    openDepotList() {
      this.drawer = true
      this.getDepotList_fun()
    },
    getDepotList_fun() {
      const params = {
        video_name: this.depotForm.video_name,
        subject: this.depotForm.subject == '全部' ? '' : this.depotForm.subject,
        pageIndex: this.queryParams.pageIndex,
        pageSize: this.queryParams.pageSize
      }
      console.log(params)
      getDepotList(params).then(res => {
        if (res.code == 200) {
          this.depot_list = res.data.list
          this.total = res.data.count
        }
      }).catch(error => {
        console.log(error)
      })
    },
    choiceQuestion(event) {
      event.stopPropagation()
    },
    // 新增子章节
    addSonchapter() {
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      const j = {
        name: '',
        url: '',
        url_name: '',
        exercises: '',
        is_show: 1,
        loading: false,
        percentage: 0,
        is_free: -1
      }
      this.chapterData.children.push(j)
      this.chapterTable.sel = JSON.parse(JSON.stringify(j))
    },
    saveRow(row, index) {
      // console.log(this.chapterTable.sel);return
      // 保存
      const data = JSON.parse(JSON.stringify(this.chapterTable.sel))
      for (const k in data) {
        row[k] = data[k] // 将sel里面的value赋值给这一行。ps(for....in..)的妙用，细心的同学发现这里我并没有循环对象row
      }
      if (data.id) { // 编辑子章节
        editLiveChapter({
          ...data,
          is_show: -1,
          course_id: this.chapterData.course_id,
        }).then(response => {
          row.is_show = -1
          this.$emit('say', this.chapterData)
        })
      } else if (this.chapterData.id) {
        const sections = {
          ...this.chapterData.children[index],
          is_show: -1,
          pid: this.chapterData.id,
          course_id: this.chapterData.course_id,
          is_live: 1
        }
        addLiveChapter(sections).then(res => { // 新增子章节
          if (res.code === 200) {
            row.is_show = -1
            this.chapterData.children[index].id = res.data
            this.$emit('say', this.chapterData)
          }
        })
      }
    },
    editRow(row) {
      // 编辑
      for (const i of this.chapterData.children) {
        if (i.is_show === 1) return this.$message.warning('请先保存当前编辑项')
      }
      this.chapterTable.sel = row
      row.is_show = 1
      this.$emit('say', this.chapterData)
    },
    deleteRow(index, rows) {
      // 删除
      const deleteData = rows.find((v, i) => i === index)
      if (deleteData.id) {
        this.$confirm('是否确认删除', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            delLiveChapter({
              // ids: [deleteData.id],
              // link_id: deleteData.course_id
              id: deleteData.id
            }).then(response => {
              rows.splice(index, 1)
              this.$emit('say', this.chapterData)
            })
          })
          .catch(function() {})
      }
    },
    editChapter(key, type) {
      const payload = {
        chapterItem: this.chapterData,
        chapterKey: key,
        type
      }
      this.$emit('dialogVisible', payload)
    },
    async httpUpload(file) {
      this.$set(this.chapterTable.sel, 'percentage', 0)
      this.$set(this.chapterTable.sel, 'loading', true)
      const client = clients()
      // 判断扩展名
      const tmpcnt = file.file.name.lastIndexOf('.')
      const exname = file.file.name.substring(tmpcnt + 1)
      const imgUrl = 'http://tw.img.twzxjy.com'
      const fileName = `static/uploadfile/${getNowDate()}/${file.file.uid}.${exname}`
      await client.multipartUpload(fileName, file.file, {
        progress: (p, cpt, res) => {
          // 获取分片上传进度、断点和返回值。
          this.$set(
            this.chapterTable.sel,
            'percentage',
            (Math.floor(p * 100) / 100) * 100
          )
          if (p === 1) {
            this.$set(this.chapterTable.sel, 'loading', false)
          }
        },
        parallel: 5, // 并发上传的分片数量
        partSize: 1024 * 1024 * 20,
        // headers,
        // 指定meta参数，自定义Object的元信息。通过head接口可以获取到Object的meta数据。
        meta: {
          year: 2020,
          people: 'test'
        },
        mime: file.type // 上传文件类型
      })
      // 填写Object完整路径，例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
      const head = await client.head(fileName)
      if (head.status === 200) {
        // 上传成功之后添加媒体库
        this.addDepotFun(`${imgUrl}/${fileName}`, file.file.name)
        // 数据赋值
        this.$set(this.chapterTable.sel, 'url', `${imgUrl}/${fileName}`)
        this.$set(this.chapterTable.sel, 'url_name', file.file.name)
      }
    },
    addDepotFun(back_name, file_name) {
      var repalce_name = back_name.replace('http://tw.img.twzxjy.com', '')
      var cover = `http://tw.img.twzxjy.com${repalce_name}?x-oss-process=video/snapshot,t_2000,f_jpg,w_800,h_600,m_fast` // 封面图
      const params = {
        video_img: cover, // 封面图
        video_name: file_name, // 文件名称
        video_path: back_name, // 文件地址
        subject: this.subject // 适用科目
      }
      // console.log(params)
      // return
      addDepot(params).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.msgSuccess('添加成功')
          this.drawer = false
        }
      })
    },
    addExercises(id) {
      this.visible = true
      this.sectionsId = id
    },
    cancel() {
      this.visible = false
    },

    submitForm(ids) {
      const parmars = {
        link_id: this.chapterItem.course_id,
        chapter_id: this.sectionsId,
        link_type: 1,
        question_bank_str: ids
      }
      chooseExercises(parmars).then(res => {
        this.visible = false
        const { children } = this.chapterData
        const childrens = children.map(item => {
          if (item.id === this.sectionsId) {
            return { ...item, is_contain_exercise: 1 }
          }
          return item
        })
        this.chapterData = {
          ...this.chapterData,
          children: childrens
        }
      })
    },
    preview(url) {
      this.showVideo = true
      this.playUrl = url
    },
    handleHideModal() {
      this.playUrl = ''
      this.showVideo = false
    }
  }
}
</script>

<style lang="scss" scoped>
.addsonchapter {
  border: 1px solid #c0c4cc;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  color: #3d64d4;
}
::v-deep .el-loading-spinner {
  top: 90%;
}
</style>
<style>
.depot-card{
    display: inline-block;
    background: #f3f3f3;
    width: 20%;
    margin: 0 10px 10px 0;
    cursor: pointer;
    text-align: center;
    padding: 10px;
    border-radius: 5px;
}
.depot-card>div{
    text-overflow: ellipsis;
    overflow: hidden;
    font-size: .8rem;
      white-space: nowrap;
}
.depot-card img{
  width: 100%;
  max-height: 120px;
}
.empty-text{
  color:gray;
  text-align: center;
  padding: 1rem;
}
</style>
